package com.hrt.common.web;

import com.btcode.common.StringUtil;
import com.btcode.db.sqlparameter.PageInfo;
import com.btcode.db.wherefilter.WhereFilterType;
import com.btcode.exception.MsgException;
import com.btcode.orm.conver.DefaultModelConver;
import com.btcode.orm.conver.DefaultValueConver;
import com.btcode.orm.conver.IModelConver;
import com.btcode.orm.conver.IValueConver;
import com.btcode.orm.filter.FilterSingle;
import com.btcode.orm.filter.IFilter;
import com.btcode.orm.model.FieldValue;
import com.btcode.orm.model.IField;
import com.btcode.orm.model.IModel;
import com.btcode.web.core.unit.WebContext;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

public class RequestUnit extends com.btcode.web.core.unit.RequestUnit {

    static IValueConver valueCover = new DefaultValueConver();

    public static <T extends IModel> T getModel(Class<T> modelClass) {

        HashMap<String, Object> value = getHashMapParmO();

        IModelConver modelConver = new DefaultModelConver();
        T model = modelConver.converORMModelHashMap(value, modelClass);

        return model;
    }

    public static <T extends IModel> List<IFilter> getModelFilter(Class<T> modelClass) {

        List<IField> fields;
        try {
            fields = modelClass.newInstance().getFields();
        }
        catch (InstantiationException | IllegalAccessException e) {
            throw new MsgException("获取model查询条件出错", e);
        }

        List<IFilter> filters = new ArrayList<>();

        for (IField field : fields) {
            String fieldName = field.getFieldName();
            String value = getString(fieldName);

            if (value != null && !value.trim().equals("")) {
                filters.add(generateFilter(field, WhereFilterType.EQUAL, value));
                continue;
            }

            value = getString(fieldName + "%");

            if (value != null && !value.trim().equals("")) {
                filters.add(generateFilter(field, WhereFilterType.LIKE_BOTH, value));
                continue;
            }

            value = getString(fieldName + ">");

            if (!StringUtil.isEmpty(value)) {
                filters.add(generateFilter(field, WhereFilterType.GREATER_THAN, value));
            }
            else {
                value = getString(fieldName + ">=");
                if (!StringUtil.isEmpty(value)) {
                    filters.add(generateFilter(field, WhereFilterType.GREATER_EQUAL_THAN, value));
                }
            }

            value = getString(fieldName + "<");

            if (!StringUtil.isEmpty(value)) {
                filters.add(generateFilter(field, WhereFilterType.LESS_THAN, value));
            }
            else {
                value = getString(fieldName + "<=");
                if (!StringUtil.isEmpty(value)) {
                    filters.add(generateFilter(field, WhereFilterType.LESS_EQUAL_THAN, value));
                }
            }
        }

        return filters;
    }

    private static IFilter generateFilter(IField field, WhereFilterType filterType, Object value) {
        Object realValue = valueCover.conveToORMValue(field, value);
        FilterSingle filter = new FilterSingle(field, filterType, realValue);
        return filter;
    }

    public static <T extends IModel> List<T> getModels(Class<T> modelClass) {

        List<T> models = new ArrayList<>();

        HashMap<String, Object> paramO = getHashMapParmO();

        T modelTemp;

        try {
            modelTemp = modelClass.newInstance();
        }
        catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }

        IModelConver modelConver = new DefaultModelConver();

        List<IField> fields = modelTemp.getFields();

        int index = 0;

        while (true) {
            HashMap<String, Object> item = new HashMap<>();
            boolean hasValue = false;

            for (IField field : fields) {
                Object v = paramO.get("data[" + index + "][" + field.getFieldName() + "]");
                item.put(field.getFieldName(), v);
                if (v != null) {
                    hasValue = true;
                }
            }

            if (hasValue) {
                T model = modelConver.converORMModelHashMap(item, modelClass);
                models.add(model);
            }
            else {
                break;
            }

            index++;
        }

        return models;
    }

    public static PageInfo getPageInfo() {

        Integer pageIndex = getInt("pageIndex");
        Integer pageSize = getInt("pageSize");

        if (pageSize == null) {
            pageSize = 99999;
        }

        PageInfo pageInfo = new PageInfo(pageSize, pageIndex);
        return pageInfo;

    }

    public static HashMap<String, Object> getHashMapParmO() {
        Enumeration<String> names = WebContext.getRequest().getParameterNames();
        try {
            WebContext.getRequest().setCharacterEncoding("utf-8");
        }
        catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HashMap<String, Object> parm = new HashMap<String, Object>();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = getString(name);

            /**
             * 约定，如果前台传了"null-value"过来，就认为这个字段需要处理，而且是处理成空。
             * 后续orm框架中，就不会忽略这个字段
             */
            if ("null-value".equals(value)) {
                parm.put(name, FieldValue.nullValue);
            }
            else {
                parm.put(name, value);
            }
        }
        return parm;
    }

}
